import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import service from '../../service'
import menuData from '../../utils/menuData'

let oldMenuData = JSON.parse(JSON.stringify(menuData))
let sideData = []
let currentTopNav = ''


const initialState = {
    token: sessionStorage.getItem("token") ? sessionStorage.getItem("token") : "",
    user: sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {},
    userInfo: {},
    routes: [],//当前路由
    childrenRoutes: [],//当前子路由
    currentSideKey: '',//当前选中侧边栏的key
    currentTopNav: '',
    menuData: [],
    topNav: [],
    sideNav: [],
    currentPageName: '',
    defaultTopNav: '',
    defaultSideNav: { selected: [''], open: [''] }
}

// 三种状态 ，在extraReducers去侦听，进行不同处理
export const userLogin = createAsyncThunk("user/userLogin", async (userInput) => {
    const res = await service.user_Login(userInput)
    return res
})

export const menuSlice = createSlice({
    name: 'menuNav',
    initialState,
    reducers: {
        // 初始化init
        setMenuData: (state) => {
            // console.log('init');
            const userData = JSON.parse(JSON.stringify(state.user))
            state.menuData = userData
            state.topNav = arrOfOneDimension(userData)

            state.userInfo = getUserInfo(userData)
            state.defaultTopNav = state.topNav[0].key + ''
            state.currentTopNav = state.topNav[0].key + ''
            currentTopNav = state.topNav[0].key + ''

            state.sideNav = sideMenuArr(state.currentTopNav, userData)
            sideData = JSON.parse(JSON.stringify(state.sideNav))


            state.routes = getRoutes(state.sideNav) //获取初始路由

            state.currentPageName = getCurrPageName(0, sideData)


            // 设置侧边栏默认第一项
            if (state.sideNav[0].id) {
                const arr = []
                for (let i = 0; i < userData.length; i++) {
                    if (!userData[i].admin) {
                        arr.push(sideMenuArr((userData[i].id + ''), userData))
                    }
                }
                arr.map(item => {
                    state.defaultSideNav.open.push(item[0].id + '')
                    state.defaultSideNav.selected.push(item[0].children[0].id + '')
                })
                // state.defaultSideNav.open.push(state.sideNav[0].id + '')
                // state.defaultSideNav.selected.push(state.sideNav[0].children[0].id + '')

            }



            // state.defaultSideNav.selected = state.sideNav[0][0].children ? state.sideNav[0][0].children[0].key + '' : ''
        },
        setCurrentTopNav: (state, action) => {
            // currentTopNav = action.payload
            const userData = JSON.parse(JSON.stringify(state.user))
            // console.log(action.payload);
            // console.log(currentTopNav);
            // state.sideNav = sideMenuArr(state.currentTopNav, userData)
            // console.log(state.sideNav);
            // const userData = JSON.parse(JSON.stringify(state.user))
            state.currentTopNav = action.payload
            state.sideNav = sideMenuArr(action.payload, userData)
            // console.log(state.sideNav);
            // sideData = state.sideNav
            // state.routes = getRoutes(sideData) //获取当前的路由

        },
        setDefaultSide: (state, action) => {
            // console.log(action.payload);
            state.defaultSideNav.selected = action.payload.selected
            state.defaultSideNav.open = action.payload.open
        },
        setCurrentPageName: (state, action) => {
            // console.log('设置当前页面名字');

            state.currentSideKey = action.payload + '' //设置当前侧边栏key
            // console.log(state.currentSideKey);
            state.currentPageName = getCurrPageName(action.payload, sideData)
        },
        setChildrenRoutes: (state, action) => {
            // console.log(action.payload);
            // state.childrenRoutes = action.payload
            state.childrenRoutes = []
            console.log(1111111);
        }
    },
    extraReducers: {
        // userLogin return 的值放在action.payload属性
        // payload: 负载
        [userLogin.fulfilled](state, { payload }) {
            state.token = payload.token
            state.user = payload.data
            // console.log(state);
            sessionStorage.setItem("token", payload.token)
            sessionStorage.setItem("user", JSON.stringify(payload.data))
            console.log("fulfilled");
        },
        [userLogin.pending](state) {
            console.log("pending");
        },
        [userLogin.rejected](state) {
            console.log("rejected");
        }
    }
})

// 菜单树提取一级菜单
function arrOfOneDimension(arr) {
    let topNavArr = []
    arr.forEach(item => {
        // console.log(oldMenuData);
        if (!item.admin) {
            let obj = {
                key: item.id,
                label: item.menuName
            }
            topNavArr.push(obj)
        }
    })
    return topNavArr
}

// 菜单树提取用户信息
function getUserInfo(arr) {
    const userInfo = []
    arr.forEach(item => {
        if (item.admin) {
            userInfo.push(item)
        }
    })
    return userInfo
}


// 菜单树提取侧边导航
function sideMenuArr(curId, allArr) {
    let sideMenu = []
    for (let i = 0; i < allArr.length; i++) {
        if (curId === (allArr[i].id + '')) {
            if (allArr[i].children) {
                oldMenuData.map(item => {
                    if (allArr[i].id === item.id) {
                        if (item.children) {
                            // console.log(JSON.parse(JSON.stringify(item.children)));
                            sideMenu = item.children
                            // return JSON.parse(JSON.stringify(item.children))
                        }
                    }
                })
            }
        }
    }

    return sideMenu
    // console.log(oldMenuData, sideMenuHandleArr(allArr));
    // return sideMenuHandleArr(allArr).map((item) => {
    //     if (Array.isArray(item.children) && item.children.length > 0) {
    //         return item.children
    //     }
    // })
}



function sideMenuHandleArr(arr) {
    if (arr instanceof Array && arr.length > 0) {
        let newArr = []
        // console.log(arr);
        arr.map((item) => {
            if (!item.admin) {
                if (item.children && item.children.length > 0) {
                    newArr.push({
                        key: item.id,
                        label: item.menuName,
                        children: [...sideMenuHandleArr(item.children)]
                    })
                } else {
                    newArr.push({
                        key: item.id,
                        label: item.menuName,
                    })
                }
            }
        })
        // console.log(newArr);
        return newArr
    }

}


function getRoutes(arr) {
    // console.log(arr);
    const routes = []
    if (Array.isArray(arr)) {
        arr.map(item => {
            // console.log(item);
            if (item.children) {
                for (let i = 0; i < item.children.length; i++) {
                    routes.push({
                        id: item.children[i].id,
                        path: item.children[i].pathRoute,
                        pagePath: item.children[i].pagePath ? item.children[i].pagePath : 'noPage'
                    })
                }
            } else if (item.pathRoute) {
                routes.push({
                    id: item.id,
                    path: item.pathRoute,
                    pagePath: item.pagePath ? item.pagePath : 'noPage'
                })
            }
        })
    }
    // console.log(routes);
    return routes
}

function getCurrPageName(id, arr) {
    // console.log(arr);
    let arrId = id ? id : 0
    let pageName = ''
    if (Array.isArray(arr)) {
        // console.log(arr);
        arr.map(item => {
            if (Array.isArray(item.children)) {
                for (let i = 0; i < item.children.length; i++) {
                    if ((arrId + '') === (item.children[i].id + '')) {
                        // console.log(item.children[0].menuName);
                        pageName = item.children[i].menuName
                    }
                }
            }
        })
    }
    // console.log(pageName);
    return pageName
}


export const { setMenuData, setCurrentTopNav, setDefaultSide, setCurrentPageName, setChildrenRoutes } = menuSlice.actions
export default menuSlice.reducer